﻿using BeetleX;
using BeetleX.Clients;
using System.Net;
using System.Threading.Tasks;
namespace Athena.Transport.BeetleX
{
    using Codec;
    using Message;
    public class BeetleXTransportMessageClientSender : ITransportMessageSender
    {
        private readonly IRpcMessageEncoder _rpcMessageEncoder;

        public AsyncTcpClient TcpClient { get; }

        public BeetleXTransportMessageClientSender(IRpcMessageEncoder rpcMessageEncoder, EndPoint endPoint)
        {
            _rpcMessageEncoder = rpcMessageEncoder;
            var ipAndPoint = endPoint.ToString().Split(':');
            TcpClient = SocketFactory.CreateClient<AsyncTcpClient>(ipAndPoint[0], int.Parse(ipAndPoint[1]));
        }

        public Task SendAsync(RpcTransportMessage rpcTransportMessage)
        {
            return SendAndFlushAsync(rpcTransportMessage);
        }

        public async Task SendAndFlushAsync(RpcTransportMessage rpcTransportMessage)
        {
            var pipestream = TcpClient.Stream.ToPipeStream();
            pipestream.WriteUTF(_rpcMessageEncoder.MessageEncodingString(rpcTransportMessage));
            await pipestream.FlushAsync();
        }
    }
}
